import { login, logout, getInfo } from '@/api/user'
import { neptuneUrl } from '@/api/lib'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: null,
    roles: null,
    neptuneUrl: null
  }
}

const state = getDefaultState()

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_NEPTUNEURL: (state, neptuneUrl) => {
    state.neptuneUrl = neptuneUrl
  }
}

const actions = {
  // 用户登录
  login({ commit }, userInfo) {
    const { loginName, loginCode } = userInfo
    return new Promise((resolve, reject) => {
      login({ loginName, loginCode })
        .then(() => {
          commit('SET_TOKEN', loginName)
          setToken(loginName)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // get user info
  getInfo({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      getInfo({ LoginName: state.token })
        .then(response => {
          if (!response) {
            return reject('请重新登录。')
          }
          commit('SET_ROLES', response.Rights)
          commit('SET_USERINFO', response)
          dispatch('category/getCategory', null, { root: true })
          dispatch('getNeptuneUrl')
          resolve(response.Rights)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          removeToken() // must remove  token  first
          resetRouter()
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_USERINFO', null)
          commit('SET_ROLES', null)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      resolve()
    })
  },

  // 获取测试调用地址
  getNeptuneUrl({ commit, state }) {
    return new Promise(() => {
      neptuneUrl().then(res => {
        commit('SET_NEPTUNEURL', res)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
